package com.example.jf.jfapp.bean.base;

import android.support.v4.app.ActivityCompat;

import com.example.jf.jfapp.PublishActivity;
import com.example.jf.jfapp.utils.PermissionUtils;

import java.lang.ref.WeakReference;

/**
 * Created by jf on 2017/7/28.
 */

public class PublishActivityPermissionsDispatcher {
    private static final int REQUEST_SHOWCAMERA = 1;

    private static final String[] PERMISSION_SHOWCAMERA = new String[] {"android.permission.READ_EXTERNAL_STORAGE"};

    private PublishActivityPermissionsDispatcher() {
    }

    public static void showCameraWithCheck(PublishActivity target) {
        if (PermissionUtils.hasSelfPermissions(target, PERMISSION_SHOWCAMERA)) {
            target.showCamera();
        } else {
            if (PermissionUtils.shouldShowRequestPermissionRationale(target, PERMISSION_SHOWCAMERA)) {
                target.showRationaleForCamera(new ShowCameraPermissionRequest(target));
            } else {
                ActivityCompat.requestPermissions(target, PERMISSION_SHOWCAMERA, REQUEST_SHOWCAMERA);
            }
        }
    }

    public static void onRequestPermissionsResult(PublishActivity target, int requestCode,
                                                  int[] grantResults) {
        switch (requestCode) {
            case REQUEST_SHOWCAMERA:
                if (PermissionUtils.verifyPermissions(grantResults)) {
                    target.showCamera();
                } else {
                    if (!PermissionUtils.shouldShowRequestPermissionRationale(target, PERMISSION_SHOWCAMERA)) {
                        target.onCameraNeverAskAgain();
                    } else {
                        target.onCameraDenied();
                    }
                }
                break;
            default:
                break;
        }
    }

    public static final class ShowCameraPermissionRequest implements PermissionRequest {
        private final WeakReference<PublishActivity> weakTarget;

        private ShowCameraPermissionRequest(PublishActivity target) {
            this.weakTarget = new WeakReference<PublishActivity>(target);
        }

        @Override
        public void proceed() {
            PublishActivity target = weakTarget.get();
            if (target == null) return;
            ActivityCompat.requestPermissions(target, PERMISSION_SHOWCAMERA, REQUEST_SHOWCAMERA);
        }

        @Override
        public void cancel() {
            PublishActivity target = weakTarget.get();
            if (target == null) return;
            target.onCameraDenied();
        }
    }
    public interface PermissionRequest {

        void proceed();

        void cancel();
    }
}
